package com.example.bluetoothlescanner;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "BLEScanner";
    private static final int REQUEST_ENABLE_BT = 1;
    private static final int PERMISSION_REQUEST_FINE_LOCATION = 1001;
    private static final long SCAN_PERIOD = 10000; // 10秒扫描时间

    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothLeScanner mBluetoothLeScanner;
    private BluetoothGatt mBluetoothGatt;
    private Handler mHandler;
    private boolean mScanning;
    private Map<String, BluetoothDevice> mLeDevices;
    private LeDeviceListAdapter mLeDeviceListAdapter;
    private List<BluetoothGattService> mGattServices;
    private CharacteristicListAdapter mCharacteristicListAdapter;
    private ServiceListAdapter mServiceListAdapter;

    private Button mScanButton;
    private ListView mDeviceListView;
    private View mConnectionPanel;
    private TextView mConnectedDeviceInfo;
    private Button mDisconnectButton;
    private ListView mServiceListView;
    private ListView mCharacteristicListView;
    private EditText mWriteValueEditText;
    private Button mWriteButton;
    private TextView mNotificationDataTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mHandler = new Handler(Looper.getMainLooper());
        mLeDevices = new HashMap<>();
        mGattServices = new ArrayList<>();

        // 初始化蓝牙适配器
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();

        // 检查设备是否支持BLE
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "设备不支持BLE", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 初始化UI组件
        initUI();
    }

    @Override
    protected void onResume() {
        super.onResume();

        // 检查蓝牙是否开启
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        } else {
            // 检查位置权限
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        PERMISSION_REQUEST_FINE_LOCATION);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopScan();
        disconnectDevice();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeGatt();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUEST_FINE_LOCATION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "位置权限已授予", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "位置权限被拒绝，无法扫描BLE设备", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_ENABLE_BT && resultCode == RESULT_CANCELED) {
            finish();
            return;
        }
    }

    private void initUI() {
        mScanButton = findViewById(R.id.btn_scan);
        mDeviceListView = findViewById(R.id.device_list);
        mConnectionPanel = findViewById(R.id.connection_panel);
        mConnectedDeviceInfo = findViewById(R.id.connected_device_info);
        mDisconnectButton = findViewById(R.id.btn_disconnect);
        mServiceListView = findViewById(R.id.service_list);
        mCharacteristicListView = findViewById(R.id.characteristic_list);
        mWriteValueEditText = findViewById(R.id.et_write_value);
        mWriteButton = findViewById(R.id.btn_write);
        mNotificationDataTextView = findViewById(R.id.tv_notification_data);

        // 设置设备列表适配器
        mLeDeviceListAdapter = new LeDeviceListAdapter(this, R.layout.listitem_device);
        mDeviceListView.setAdapter(mLeDeviceListAdapter);
        mDeviceListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final BluetoothDevice device = mLeDeviceListAdapter.getItem(position);
                if (device == null) return;

                stopScan();
                connectToDevice(device);
            }
        });

        // 设置服务列表适配器
        mServiceListAdapter = new ServiceListAdapter(this, R.layout.listitem_service);
        mServiceListView.setAdapter(mServiceListAdapter);
        mServiceListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothGattService service = mServiceListAdapter.getItem(position);
                if (service != null) {
                    displayCharacteristics(service.getCharacteristics());
                }
            }
        });

        // 设置特征列表适配器
        mCharacteristicListAdapter = new CharacteristicListAdapter(this, R.layout.listitem_characteristic);
        mCharacteristicListView.setAdapter(mCharacteristicListAdapter);
        mCharacteristicListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothGattCharacteristic characteristic = mCharacteristicListAdapter.getItem(position);
                if (characteristic != null) {
                    setCharacteristicNotification(characteristic, true);
                }
            }
        });

        // 扫描按钮点击事件
        mScanButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mScanning) {
                    stopScan();
                } else {
                    startScan();
                }
            }
        });

        // 断开连接按钮点击事件
        mDisconnectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                disconnectDevice();
            }
        });

        // 写入按钮点击事件
        mWriteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String value = mWriteValueEditText.getText().toString();
                if (!value.isEmpty() && mCharacteristicListAdapter.getSelectedCharacteristic() != null) {
                    writeCharacteristic(mCharacteristicListAdapter.getSelectedCharacteristic(), value);
                } else {
                    Toast.makeText(MainActivity.this, "请选择特征并输入要写入的值", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void startScan() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        // 清空设备列表
        mLeDevices.clear();
        mLeDeviceListAdapter.clear();

        // 配置扫描设置
        ScanSettings settings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .build();

        // 开始扫描
        mBluetoothLeScanner.startScan(null, settings, mScanCallback);
        mScanning = true;
        mScanButton.setText("停止扫描");

        // 10秒后停止扫描
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                stopScan();
            }
        }, SCAN_PERIOD);
    }

    private void stopScan() {
        if (mScanning) {
            mBluetoothLeScanner.stopScan(mScanCallback);
            mScanning = false;
            mScanButton.setText("开始扫描");
        }
    }

    private void connectToDevice(BluetoothDevice device) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT)
                != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "没有蓝牙连接权限", Toast.LENGTH_SHORT).show();
            return;
        }

        // 关闭之前的连接
        if (mBluetoothGatt != null) {
            mBluetoothGatt.close();
            mBluetoothGatt = null;
        }

        // 连接到设备
        mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
        mConnectedDeviceInfo.setText("已连接设备: " + device.getName() + " (" + device.getAddress() + ")");
        mConnectionPanel.setVisibility(View.VISIBLE);
    }

    private void disconnectDevice() {
        if (mBluetoothGatt != null) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT)
                    != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            mBluetoothGatt.disconnect();
            mConnectionPanel.setVisibility(View.GONE);
            mServiceListAdapter.clear();
            mCharacteristicListAdapter.clear();
            mNotificationDataTextView.setText("等待通知...");
        }
    }

    private void closeGatt() {
        if (mBluetoothGatt != null) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT)
                    != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            mBluetoothGatt.close();
            mBluetoothGatt = null;
        }
    }

    private void displayServices(List<BluetoothGattService> services) {
        mGattServices = services;
        mServiceListAdapter.clear();
        mCharacteristicListAdapter.clear();

        for (BluetoothGattService service : services) {
            mServiceListAdapter.add(service);
        }
        mServiceListAdapter.notifyDataSetChanged();
    }

    private void displayCharacteristics(List<BluetoothGattCharacteristic> characteristics) {
        mCharacteristicListAdapter.clear();

        for (BluetoothGattCharacteristic characteristic : characteristics) {
            mCharacteristicListAdapter.add(characteristic);
        }
        mCharacteristicListAdapter.notifyDataSetChanged();
    }

    private void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
                                               boolean enabled) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT)
                != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        if (mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothGatt not initialized");
            return;
        }

        mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);

        // 对于通知特性，还需要配置客户端配置描述符
        UUID descriptorUuid = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
        if (characteristic.getDescriptors() != null &&
                (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
            for (android.bluetooth.BluetoothGattDescriptor descriptor : characteristic.getDescriptors()) {
                if (descriptor.getUuid().equals(descriptorUuid)) {
                    descriptor.setValue(android.bluetooth.BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                    mBluetoothGatt.writeDescriptor(descriptor);
                }
            }
        }

        mCharacteristicListAdapter.setSelectedCharacteristic(characteristic);
    }

    private void writeCharacteristic(BluetoothGattCharacteristic characteristic, String value) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT)
                != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        if (mBluetoothGatt == null) {
            Log.w(TAG, "BluetoothGatt not initialized");
            return;
        }

        // 设置要写入的值
        characteristic.setValue(value);

        // 写入特征
        boolean result = mBluetoothGatt.writeCharacteristic(characteristic);
        Log.d(TAG, "写入特征结果: " + result);

        if (result) {
            Toast.makeText(this, "正在写入特征值...", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "写入特征失败", Toast.LENGTH_SHORT).show();
        }
    }

    // 设备扫描回调
    private final ScanCallback mScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            addDevice(result.getDevice());
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
            for (ScanResult result : results) {
                addDevice(result.getDevice());
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            Log.e(TAG, "扫描失败，错误码: " + errorCode);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "扫描失败", Toast.LENGTH_SHORT).show();
                    mScanning = false;
                    mScanButton.setText("开始扫描");
                }
            });
        }

        private void addDevice(BluetoothDevice device) {
            if (!mLeDevices.containsKey(device.getAddress())) {
                mLeDevices.put(device.getAddress(), device);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mLeDeviceListAdapter.add(device);
                        mLeDeviceListAdapter.notifyDataSetChanged();
                    }
                });
            }
        }
    };
    // GATT回调
    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);

            if (newState == BluetoothProfile.STATE_CONNECTED) {
                Log.i(TAG, "连接成功，开始发现服务");
                if (ActivityCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                gatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                Log.i(TAG, "已断开连接");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mConnectionPanel.setVisibility(View.GONE);
                        mServiceListAdapter.clear();
                        mCharacteristicListAdapter.clear();
                        mNotificationDataTextView.setText("等待通知...");
                    }
                });
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);

            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.i(TAG, "服务发现成功");
                final List<BluetoothGattService> services = gatt.getServices();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        displayServices(services);
                    }
                });
            } else {
                Log.w(TAG, "服务发现失败，状态码: " + status);
            }
        }

        @Override
        public void onCharacteristicRead(BluetoothGatt gatt,
                                         BluetoothGattCharacteristic characteristic,
                                         int status) {
            super.onCharacteristicRead(gatt, characteristic, status);

            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.i(TAG, "特征读取成功");
                final String data = new String(characteristic.getValue());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "读取特征值: " + data, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt,
                                          BluetoothGattCharacteristic characteristic,
                                          int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);

            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.i(TAG, "特征写入成功");
                final String data = new String(characteristic.getValue());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "写入特征值成功: " + data, Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                Log.w(TAG, "特征写入失败，状态码: " + status);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "写入特征值失败", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                                            BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);

            Log.i(TAG, "特征值已更改");
            final String data = new String(characteristic.getValue());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mNotificationDataTextView.setText("收到通知: " + data);
                }
            });
        }
    };

    // 设备列表适配器
    private static class LeDeviceListAdapter extends ArrayAdapter<BluetoothDevice> {
        private final List<BluetoothDevice> mLeDevices;
        private final int mResource;

        public LeDeviceListAdapter(Context context, int resource) {
            super(context, resource);
            mLeDevices = new ArrayList<>();
            mResource = resource;
        }

        @Override
        public void add(BluetoothDevice device) {
            if (!mLeDevices.contains(device)) {
                mLeDevices.add(device);
                super.add(device);
            }
        }

        @Override
        public int getCount() {
            return mLeDevices.size();
        }

        @Override
        public BluetoothDevice getItem(int position) {
            return mLeDevices.get(position);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;

            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(mResource, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.deviceName = convertView.findViewById(R.id.device_name);
                viewHolder.deviceAddress = convertView.findViewById(R.id.device_address);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            BluetoothDevice device = mLeDevices.get(position);
            final String deviceName = device.getName();

            if (deviceName != null && deviceName.length() > 0) {
                viewHolder.deviceName.setText(deviceName);
            } else {
                viewHolder.deviceName.setText("未知设备");
            }

            viewHolder.deviceAddress.setText(device.getAddress());

            return convertView;
        }

        private static class ViewHolder {
            TextView deviceName;
            TextView deviceAddress;
        }
    }

    // 服务列表适配器
    private static class ServiceListAdapter extends ArrayAdapter<BluetoothGattService> {
        private final List<BluetoothGattService> mServices;
        private final int mResource;

        public ServiceListAdapter(Context context, int resource) {
            super(context, resource);
            mServices = new ArrayList<>();
            mResource = resource;
        }

        @Override
        public void add(BluetoothGattService service) {
            if (!mServices.contains(service)) {
                mServices.add(service);
                super.add(service);
            }
        }

        @Override
        public int getCount() {
            return mServices.size();
        }

        @Override
        public BluetoothGattService getItem(int position) {
            return mServices.get(position);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;

            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(mResource, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.serviceUuid = convertView.findViewById(R.id.service_uuid);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            BluetoothGattService service = mServices.get(position);
            viewHolder.serviceUuid.setText("服务: " + service.getUuid().toString());

            return convertView;
        }

        private static class ViewHolder {
            TextView serviceUuid;
        }
    }

    // 特征列表适配器
    private static class CharacteristicListAdapter extends ArrayAdapter<BluetoothGattCharacteristic> {
        private final List<BluetoothGattCharacteristic> mCharacteristics;
        private final int mResource;
        private BluetoothGattCharacteristic mSelectedCharacteristic;

        public CharacteristicListAdapter(Context context, int resource) {
            super(context, resource);
            mCharacteristics = new ArrayList<>();
            mResource = resource;
        }

        @Override
        public void add(BluetoothGattCharacteristic characteristic) {
            if (!mCharacteristics.contains(characteristic)) {
                mCharacteristics.add(characteristic);
                super.add(characteristic);
            }
        }

        @Override
        public int getCount() {
            return mCharacteristics.size();
        }

        @Override
        public BluetoothGattCharacteristic getItem(int position) {
            return mCharacteristics.get(position);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;

            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(mResource, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.charUuid = convertView.findViewById(R.id.char_uuid);
                viewHolder.charProperties = convertView.findViewById(R.id.char_properties);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            BluetoothGattCharacteristic characteristic = mCharacteristics.get(position);
            viewHolder.charUuid.setText("特征: " + characteristic.getUuid().toString());

            StringBuilder properties = new StringBuilder();
            if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_READ) != 0) {
                properties.append("可读 ");
            }
            if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE) != 0) {
                properties.append("可写 ");
            }
            if ((characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY) != 0) {
                properties.append("可通知 ");
            }
            viewHolder.charProperties.setText("属性: " + properties.toString());

            // 高亮显示选中的特征
            if (mSelectedCharacteristic != null &&
                    mSelectedCharacteristic.getUuid().equals(characteristic.getUuid())) {
                convertView.setBackgroundColor(convertView.getContext().getResources()
                        .getColor(R.color.selected_background));
            } else {
                convertView.setBackgroundColor(convertView.getContext().getResources()
                        .getColor(android.R.color.transparent));
            }

            return convertView;
        }

        public void setSelectedCharacteristic(BluetoothGattCharacteristic characteristic) {
            mSelectedCharacteristic = characteristic;
            notifyDataSetChanged();
        }

        public BluetoothGattCharacteristic getSelectedCharacteristic() {
            return mSelectedCharacteristic;
        }

        private static class ViewHolder {
            TextView charUuid;
            TextView charProperties;
        }
    }
}
